<?php
/**
 * User: XiaoFei Zhai
 * Date: 17/9/27
 * Time: 上午8:53
 */

namespace App\Models;


use App\Searchable;
use Carbon\Carbon;
use Elasticsearch\Common\Exceptions\Missing404Exception;
use GenPwdIsvParamDto;
use Illuminate\Database\Eloquent\Model;

use TbkTpwdCreateRequest;
use TopClient;
use WirelessShareTpwdCreateRequest;

class ChosenGoods extends Model
{

    protected $searchable = [
        'columns' => [
            'title' => 8,
        ],
    ];


    public static function news($num=4){
        return static::where(['status'=>1])->orderBy('created_at', 'desc')->take($num)->get();
    }


    public function setPicturesAttribute($pictures)
    {
        if (is_array($pictures)) {
            $this->attributes['pictures'] = json_encode($pictures);
        }
    }

    public function getPicturesAttribute($pictures)
    {
        $pictures                           =   json_decode($pictures, true);
        foreach ($pictures as $k=>$v){
            $pictures[$k]                   =   get_image_url($v);
        }
        return $pictures;
    }
    public function toSearchableArray()
    {
        return [
            'title'             =>  $this->title,
            'price'             =>  (double)$this->price,
            'created_at'        =>  Carbon::createFromFormat('Y-m-d h:i:s',$this->created_at)->timestamp,
            'view'              =>  $this->view
        ];
    }

    public static function getByNumIid($numIid){
        return static ::where(['original_id'=>$numIid])->first();
    }

    public static function info($id){
        return static ::where(['id'=>$id])->first();
    }
    public function getCoverAttribute($cover)
    {
        return get_image_url($cover);
    }
    public function getCouponAmountAttribute($amount){
        return number_format($amount,0);
    }
    public static function setCouponPrice($items){
        foreach ($items as  $k => $v){
            if(!empty($v->coupon_end_time)){
                if (Carbon::now()->gt(new Carbon($v->coupon_end_time))){
                    $items[$k]->coupon_status        =   0;
                    $items[$k]->save();
                }
            }
            if($v->coupon_status > 0){
                $items[$k]->coupon_price        =   number_format($v->price-$v->coupon_amount,1);
            }else{
                $items[$k]->coupon_price        =   $v->price;
            }
            $items[$k]->coupon_amount           =   number_format($v->coupon_amount,0);
        }
        return $items;
    }

    public static function getCouponGoods(){
        $list                                   =   static ::where(['coupon_status'=>1])->take(4)->get();
        if($list){
            $list                               =   static ::setCouponPrice($list);
        }
        return $list;
    }

    public static function getTpwd($url,$text){
        $c = new TopClient;
        $c->appkey                      = config('taobao.app_key');
        $c->secretKey                   = config('taobao.app_secret');
        $c->format                      =   'json';
        $req = new TbkTpwdCreateRequest;
      //  $req->setUserId("123");
        $req->setText($text);
        $req->setUrl($url);
    //    $req->setLogo("https://uland.taobao.com/");
        $req->setExt("{}");

        $resp = $c->execute($req);

        if(isset($resp->code)){
            return '';
        }

        return $resp->data->model;
    }

    public function updateToEs(){
        $searchable                         =   new Searchable();
        try{
            $data                           =   $searchable->get($this->id);
            $searchable->update($this);
        }catch (Missing404Exception $exception){
            if(!$searchable->exist()){
                $searchable->create();
            }
            $searchable->insert($this);
        }
    }
    public function search($keyword){
        $searchable                         =   new Searchable();
        $in                                 =   $searchable->search($keyword);
        return $this->whereIn('id',$in)->get();

    }
    public function delete()
    {
        return parent::delete(); // TODO: Change the autogenerated stub
    }
    public function deleteFromEs(){
        if($this->status<1){
            $searchable                         =   new Searchable();
            return $searchable->delete($this);
        }
    }
//    public function save(array $options = [])
//    {
//        $res= parent::save($options); // TODO: Change the autogenerated stub
//        if($this->status <1){
//            $this->deleteFromEs();
//        }else{
//            $this->updateToEs();
//        }
//
//        return $res;
//    }
}